﻿using Common.Communal;
using ERP.Domain.Scheduling;
using ERP.Domain.System;
using MediatR;
using Scheduling.Api.Read.Application.Command.TeamCommand;
using SqlSugar;

namespace Scheduling.Api.Read.Application.CommandHandlers.TeamHandler
{
    public class TeamMemberCreateCommandHandler : IRequestHandler<TeamMemberCreateCommand, ApiResult<List<TeamMemberWithTeam>>>
    {
        // 仅供 SqlSugar 映射使用的轻量实体，列名与数据库保持一致
        private class TeamMemberSugar
        {
            public int MemberId { get; set; }
            public int TeamId { get; set; }
            public int Employee { get; set; }
            public bool? IsDelete { get; set; }
        }

        public TeamMemberCreateCommandHandler(ISqlSugarClient sqlSugar)
        {
            SqlSugar = sqlSugar;
        }

        public ISqlSugarClient SqlSugar { get; }

        public Task<ApiResult<List<TeamMemberWithTeam>>> Handle(TeamMemberCreateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<TeamMemberWithTeam>> result = new ApiResult<List<TeamMemberWithTeam>>();
            result.Code = EnumCode.Ok;
            result.Message = "班组成员显示成功";

            // 多表联查：TeamMember -> Team -> TeamType, UserRole -> User -> Role
            var query = SqlSugar.Queryable<TeamMemberSugar>().AS("TeamMember")
                .InnerJoin<Team>((m, t) => m.TeamId == t.TeamId)
                .InnerJoin<TeamType>((m, t, tt) => t.TeamTypeId == tt.TeamTypeId)
                .InnerJoin<UserRole>((m, t, tt, ur) => ur.UserId == m.Employee)
                .InnerJoin<User>((m, t, tt, ur, u) => u.Id == ur.UserId)
                .InnerJoin<Role>((m, t, tt, ur, u, r) => r.Id == ur.RoleId)
                .Where((m, t, tt, ur, u, r) => 
                    m.IsDelete == false && 
                    t.IsDelete == false && 
                    tt.IsDelete == false &&
                    u.IsDeleted == false && 
                    r.IsDeleted == false && 
                    r.RoleName == "员工");

            // 如果指定了TeamId，则添加筛选条件
            if (request.TeamId.HasValue)
            {
                query = query.Where((m, t, tt, ur, u, r) => m.TeamId == request.TeamId.Value);
            }

            // 选择所需字段
            var list = query.Select<TeamMemberWithTeam>("m.MemberId, m.TeamId, m.Employee as EmployeeId, t.TeamName, tt.TeamTypeName, u.UserName, u.UserAccount, u.UserPhone, r.RoleName")
                .ToList();

            result.Data = list;
            return Task.FromResult(result);
        }
    }
}
